﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace AutoUpdateTool
{
    public class XmlHelper
    {
        #region 反序列化

        /// <summary>
        /// 字符串反序列化
        /// </summary>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            using (StringReader sr = new StringReader(xml))
            {
                XmlSerializer xmldes = new XmlSerializer(typeof(T));
                return (T)xmldes.Deserialize(sr);
            }
        }

        /// <summary>
        /// 流反序列化
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static T Deserialize<T>(Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(typeof(T));
            return (T)xmldes.Deserialize(stream);
        }
        #endregion

        #region 序列化

        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serialize(object obj, bool hideXmlDec = false, bool indent = false)
        {
            MemoryStream stream = new MemoryStream();
            
            try
            {
                XmlSerializer xml = new XmlSerializer(obj.GetType());
                // 强制指定命名空间，覆盖默认的命名空间
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add(string.Empty, string.Empty);
                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                xmlWriterSettings.Encoding = new UTF8Encoding(false);//设置编码,不能用Encoding.UTF8,会导致带有BOM标记 
                xmlWriterSettings.Indent = indent;//设置自动缩进

                // true删除 false添加 XmlDeclaration：<?xml version="1.0" encoding="utf-16"?>
                xmlWriterSettings.OmitXmlDeclaration = hideXmlDec;
                //xmlWriterSettings.NewLineChars = "\r\n";
                //xmlWriterSettings.NewLineHandling = NewLineHandling.None;

                using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
                {
                    //序列化对象
                    xml.Serialize(xmlWriter, obj, namespaces);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            stream.Dispose();
            return str;
        }

        #endregion
    }
}
